package com.guaoran.source.mybatis.v2.execute;

import com.guaoran.source.mybatis.v2.config.Configuration;
import com.guaoran.source.mybatis.v2.mapper.MapperRegistry;
import com.guaoran.source.mybatis.v2.statement.StatementHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/5/26 22:14
 */
public class CacheExecutor implements Executor {
    private Configuration configuration;
    public CacheExecutor(Configuration configuration) {
        this.configuration = configuration;
    }
    private DefaultExecutor delegate;
    private Map<String,Object> localCache = new HashMap();

    public CacheExecutor(DefaultExecutor delegate) {
        this.delegate = delegate;
    }

    @Override
    public <T> T query(MapperRegistry.KnownMappersInfo knownMappersInfo, Object paramment) throws InvocationTargetException, SQLException, IllegalAccessException, NoSuchMethodException {
        StatementHandler statementHandler = new StatementHandler(configuration);
        Object result = localCache.get(knownMappersInfo.getSql());
        if( null != result){
            System.out.println("缓存命中");
            return (T)result;
        }
        result =  (T) delegate.query(knownMappersInfo,paramment);
        localCache.put(knownMappersInfo.getSql(),result);
        return (T) result;
    }

    @Override
    public <T> List<T> queryList(MapperRegistry.KnownMappersInfo knownMappersInfo, Object paramment) throws InvocationTargetException, SQLException, IllegalAccessException, NoSuchMethodException {
        StatementHandler statementHandler = new StatementHandler(configuration);
        Object result = localCache.get(knownMappersInfo.getSql());
        if( null != result){
            System.out.println("缓存命中");
            return (List<T>) result;
        }
        result =  (T) delegate.queryList(knownMappersInfo,paramment);
        localCache.put(knownMappersInfo.getSql(),result);
        return (List<T>) result;
    }
}
